<template>
  <div class="full-msg-container">
    <el-card>
      <template slot="header">
        <div class="card-header">
          <span>全部消息</span>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索消息..."
            prefix-icon="el-icon-search"
            style="width: 200px; display: inline-block; margin-left: 20px;"
          />
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="messages"
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column
          prop="title"
          label="消息标题"
          width="300"
        />
        <el-table-column
          prop="content"
          label="消息内容"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div v-html="scope.row.content"></div>
          </template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="消息类型"
          width="100"
          :formatter="formatType"
        />
        <el-table-column
          prop="msgTime"
          label="发送时间"
          width="180"
        />
        <el-table-column
          prop="read"
          label="阅读状态"
          width="100"
          :formatter="formatReadStatus"
        />
      </el-table>
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
      <div v-else class="no-data">暂无消息</div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'FullMsg',
  data() {
    return {
      user: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      messages: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchKeyword: ''
    };
  },
  created() {
    this.loadMessages();
  },
  methods: {
    loadMessages() {
      this.loading = true;
      // 调用后端API获取消息列表
      this.$request.get('/messageBox/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword,
          userId: this.user.id
        }
      }).then(res => {
        if (res.code === '200') {
          this.messages = res.data || [];
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.msg || '获取消息列表失败');
        }
      }).catch(error => {
        console.error('获取消息列表失败:', error);
        this.$message.error('获取消息列表失败，请重试');
      }).finally(() => {
        this.loading = false;
      });
    },
    handleRowClick(row) {
      // 点击消息行，跳转到消息详情页面
      // 先更新消息已读状态
      this.updateMessageReadStatus(row.id);
      // 跳转到消息详情页面
      this.$router.push({
        path: '/message/detail',
        query: { id: row.id, t: Date.now() },
        params: { messageId: row.id }
      });
    },
    updateMessageReadStatus(messageId) {
      // 发送请求到后端更新消息已读状态
      this.$request.post('/messageBox/read', {
        id: messageId
      }).then(res => {
        console.log('消息已读状态更新成功:', res.data);
        // 更新本地消息状态
        const msg = this.messages.find(m => m.id === messageId);
        if (msg) {
          msg.read = true;
        }
      }).catch(error => {
        console.error('消息已读状态更新失败:', error);
      });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadMessages();
    },
    handleCurrentChange(current) {
      this.currentPage = current;
      this.loadMessages();
    },
    formatType(row) {
      const typeMap = {
        'system': '系统消息',
        'chat': '聊天消息',
        'notice': '通知消息'
      };
      return typeMap[row.type] || row.type;
    },
    formatReadStatus(row) {
      return row.read ? '已读' : '未读';
    }
  },
  watch: {
    searchKeyword(val) {
      // 搜索关键词变化时，重新加载消息列表
      this.currentPage = 1;
      this.loadMessages();
    }
  }
};
</script>

<style scoped>
.full-msg-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.no-data {
  text-align: center;
  padding: 40px 0;
  color: #999;
}
</style>